package gherkinedit.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StringUtils {
	public static int calculateLevinstheinDistance(String string1, String string2) {
		// declare variables
		int cost;
		int[][] matrix;
		
		// Initialize matrix
		matrix = new int[string1.length()+1][string2.length()+1];
		for (int i = 0; i <= string1.length(); i++) {
			matrix[i][0] = i;
		}
		for (int i = 0; i <= string2.length(); i++) {
			matrix[0][i] = i;
		}
		
		// Calculate matrix
		for (int i = 1; i <= string1.length(); i++) {
			for (int j = 1; j <= string2.length(); j++) {
				//calculate cost
				if (string1.charAt(i-1) == string2.charAt(j-1)) {
					cost = 0;
				} else {
					cost = 1;
				}
				//calculate current cell value
				matrix[i][j] = getMinimum(matrix[i-1][j]+1, matrix[i][j-1]+1, matrix[i-1][j-1]+cost);
			}
		}
		
//		// Print matrix for test
//		String print = "";
//		for(int i=0; i<=string2.length(); i++) {
//			for(int j=0; j<=string1.length(); j++) {
//				print = print+matrix[j][i]+" ";
//			}
//			print = print+'\n';
//		}
//		System.out.println(print);
		
		return matrix[string1.length()][string2.length()];
	}
	
	public static List<String> sortStrByAscDistToStr(List<String> strings, String string) {
		List<StringWithDistance> stringAndDistanceList = new ArrayList<StringWithDistance>();
		for (int i=0; i<strings.size(); i++) {
			stringAndDistanceList.add(new StringWithDistance(strings.get(i), Integer.parseInt(String.valueOf(calculateLevinstheinDistance(strings.get(i), string)))));
		}

        Collections.sort(stringAndDistanceList, new StringWithDistanceComparator());
        
        List<String> sortedStrings = new ArrayList<String>();
        for (StringWithDistance swd : stringAndDistanceList) {
        	sortedStrings.add(swd.string);
        }

        return sortedStrings;
	}
	
	private static int getMinimum(int a, int b, int c) {
		int minimum = a;
		if (b < minimum) minimum = b;
		if (c < minimum) minimum = c;
		return minimum;
	}
}
